<template>
  <div class="avator">
    <el-card shadow="never">
      <template #header>
        <div class="header">
          <span>更换头像</span>
        </div>
      </template>
      <div>
        <!-- 图片，用来展示用户选择的头像 -->
        <img :src="Avatar" alt="" style="width:250px;"  v-if="Avatar"/>
        <img src="../../../assets/images/avatar.jpg" style="width:250px;" alt=""  v-else />

        <!-- 按钮区域 -->
        <div class="btn-box">
          <input type="file" style="display:none;" ref="refIpt" @change="onIptChange">
          <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择头像</el-button>
          <el-button type="primary" plain icon="el-icon-upload" :disabled="Avatar===''"  @click="upLoadAvatar">上传图片</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getUserinfo, updateAvatar } from '@/api/user'
export default {
  name: 'avator-page',
  data () {
    return {
      Avatar: ''
    }
  },
  created () {
    this.getInfo()
  },
  methods: {
    async getInfo () {
      const { data } = await getUserinfo()
      this.Avatar = data.user_pic
    },
    chooseImg () {
      this.$refs.refIpt.click()
    },
    onIptChange (e) {
      if (e.target.files.length === 0) {
        this.Avatar = ''
      } else {
        const reader = new FileReader()
        reader.readAsDataURL(e.target.files[0])
        reader.onload = () => {
          this.Avatar = reader.result
        }
      }
    },
    // 点击上传头像
    async upLoadAvatar () {
      const res = await updateAvatar({ avatar: this.Avatar })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.$store.commit('user/getAvatar', this.Avatar)
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
    span {
      font-size: 16px;
      color: #131523;
      font-weight: 500;
    }
  }
  .btn-box {
    margin-top: 20px;
  }
}
</style>
